package com.jrfid.smartcabinet.demo.model

import android.os.Parcel
import android.os.Parcelable
import com.blankj.utilcode.util.StringUtils
import com.jrfid.smartcabinet.demo.R
import java.io.Serializable

class TagInfoModel() : Parcelable, Comparable<TagInfoModel> {
    var rssiMin: Int? = null
    var rssiMax: Int? = null
    var epc: String = ""
    var count: Int = 1
    var cabinetName: String = ""
    var cabinetIp: String? = null
    var cabinetPort: Int? = null
    var cabinetAddress: Int = 0x01

    constructor(parcel: Parcel) : this() {
        rssiMin = parcel.readInt()
        rssiMin = if (rssiMin == -1) null else rssiMin
        rssiMax = parcel.readInt()
        rssiMax = if (rssiMax == -1) null else rssiMax
        epc = parcel.readString() ?: ""
        count = parcel.readInt()
        cabinetName = parcel.readString() ?: ""
        cabinetIp = parcel.readString()
        cabinetPort = parcel.readInt()
        cabinetAddress = parcel.readInt()
    }

    fun getRssiText(): String {
        return "Rssi：${rssiMin} ~ ${rssiMax}dBm"
    }

    fun getCountText(): String {
        return StringUtils.getString(R.string.text_rfid_read_count, count)
    }

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeInt(rssiMin ?: -1)
        parcel.writeInt(rssiMax ?: -1)
        parcel.writeString(epc)
        parcel.writeInt(count)
        parcel.writeString(cabinetName)
        parcel.writeString(cabinetIp)
        cabinetPort?.let {
            parcel.writeInt(it)
        }
        parcel.writeInt(cabinetAddress)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<TagInfoModel> {
        override fun createFromParcel(parcel: Parcel): TagInfoModel {
            return TagInfoModel(parcel)
        }

        override fun newArray(size: Int): Array<TagInfoModel?> {
            return arrayOfNulls(size)
        }
    }

    override fun compareTo(other: TagInfoModel): Int {
        for (i in 0..23) {
            if (epc.length >= i + 1 && other.epc.length >= i + 1) {
                val n = epc[i].toString().toInt(16)
                val o = other.epc[i].toString().toInt(16)
                if (n - o != 0) {
                    return n - o
                }
            } else {
                val n = epc[i - 1].toString().toInt(16)
                val o = other.epc[i - 1].toString().toInt(16)
                return n - o
            }
        }
        return 0
    }
}
